﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iReaper.IndexService.Common.TaskEngine;

namespace iReaper.IndexService.Common.TaskEngine
{
    public class TaskEngine
    {
        private ITask[] m_tasks;
        private Queue<EventItem>[] m_eventTbl;
        static EventItem[] g_zeroArray = new EventItem[0];
        public TaskEngine(ITask[] task)
        {
            m_tasks = task;
            if (task == null) throw new ArgumentNullException("task");

            m_eventTbl = new Queue<EventItem>[task.Length];
            for (int i = 0; i < task.Length; i++)
            {
                // Create queues and init each task object
                var List = new Queue<EventItem>();
                m_eventTbl[i] = List;
            }

            for (int i = 0; i < task.Length; i++)
            {
                m_tasks[i].Initialize(i == 0 ? null : m_eventTbl[i - 1], m_eventTbl[i], i == 0 ? null : m_tasks[i - 1]);
                m_tasks[i].Start();
            }
        }

        public void Run()
        {
            System.Threading.Thread process = new System.Threading.Thread(ProcessEntry);
            process.Start();

            while (true)
            {
                System.Threading.Thread.Sleep(10000);
                // Check if all tasks are complete
                if (m_tasks.Any(e => !e.IsComplete))
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }

        private void ProcessEntry()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(5000);
                // Check each array
                for (int i = 0; i < m_eventTbl.Length; i++)
                {
                    var list = m_eventTbl[i];
                    Console.Write("{0},", list.Count);
                }
                Console.Write("\r");
            }
        }

    }
}
